import React, { useCallback, useEffect, useState } from "react";
import { LibAppView, utils } from "@/lib";
import { Cascader } from "antd";


interface Option {
    value?: string | number | null;
    label: React.ReactNode;
    children?: Option[];
    isLeaf?: boolean;
    dep: number;
}
interface IRegionPickerProps {
    onChange?: any;
    value?: string[];
    placeholder?: string;
}

const RegionPicker = LibAppView.withService<IRegionPickerProps>()((props) => {

    const [ listData, setListData ] = useState<Option[]>(() => utils.toJSON(sessionStorage.getItem("regionData") as string, []));

    const loadData = useCallback((selectedOptions: Option[], skipUpdate: boolean) => {
        return new Promise<any[]>((resolve, reject) => {
            const targetOption = selectedOptions[selectedOptions.length - 1];
            if(!targetOption?.children || targetOption.children?.length === 0) {
                props.withServiceApi.send({
                    endPoint: "setting.regionList",
                    uri: {
                        pid: targetOption?.value ?? '0'
                    }
                }).then(({ data }: any) => {
                    const listDataNew: any[] = data || [];
                    const curDeap = targetOption?.dep ? targetOption.dep + 1 : 1;
                    const optionList: Option[] = listDataNew.map((item) => ({
                        label: item.title,
                        value: item.code,
                        isLeaf: curDeap > 2,
                        dep: curDeap,
                        children: []
                    }));

                    if(targetOption) {
                        targetOption.children = optionList;
                        !skipUpdate && setListData([...listData]);
                    } else {
                        !skipUpdate && setListData(optionList);
                    }
                    resolve(optionList);
                }).catch((err) => {
                    console.error(err);
                    reject(err);
                });
            }
        })
    }, [listData]);
    const onChangeEvent = useCallback((data: any) => {
        typeof props.onChange === "function" && props.onChange(data);
    }, [props]);
    useEffect(() => {
        loadData([], true).then((listData: any[]) => {
            // 目前只保留江苏省
            const proviceList = listData.filter((item) => item.value === '320000');
            const proviceCode = props.value?.[0];
            if(proviceCode) {
                for(const item of proviceList) {
                    if(item.value === proviceCode) {
                        loadData([item], true).then((subList: any[]) => {
                            const cityCode = props.value?.[1];
                            item.children = subList || [];
                            if(cityCode) {
                                for(const item2 of item.children) {
                                    if(item2.value === cityCode) {
                                        loadData([item, item2], true).then((subList2: any[]) => {
                                            item2.children = subList2 || [];
                                            setListData([...proviceList]);
                                        });
                                        return;
                                   }
                                }
                            }
                            setListData([...proviceList]);
                        });
                        return;
                    }
                }
            }
            setListData([...proviceList]);
        });
    }, []);
    useEffect(() => {
        listData.length > 0 && sessionStorage.setItem("regionData", JSON.stringify(listData));
    }, [listData]);

    return <Cascader
        defaultValue={props.value}
        options={listData}
        onChange={onChangeEvent}
        loadData={loadData as any}
        placeholder={props.placeholder || "请选择省/市/区"}
        changeOnSelect
    />
});


export default RegionPicker;
